<template>
    <div class="w750" :class="[fightDetail ? '' : 'white-bg', themes.theme]">
        <!-- 拉新通知栏 -->
        <div v-if="fightDetail.groupModel == 'RECRUITMENT_GROUP'">
            <van-notice-bar scrollable text="该团仅限新用户参团，任意用户可发团（新用户指未在商城下过有效订单的" />
        </div>
        <div class="fight-success">
            <div class="part-in-fight">
                <div class="ser-list" @click="$toPage('/fightDetail', { id: fightDetail.mergeId })">
                    <div class="search-con">
                        <div class="pro-mes">
                            <div class="pro-img">
																<legend-image :pic="fightDetail.groupPic" :isJD="fightDetail.prodSource == 'JD'" :options="{w:90,h:90}" />
                                <!-- <img :src="$imgUrlHead + currentSku.pic" srcset alt /> -->
                            </div>
                            <div class="pro-name">
                                <div class="name">
                                    <span class="act-tag">{{ fightDetail.peopleNumber }}人团</span>
                                    {{ currentSku.name }}
                                </div>
                                <div class="pro-price">
                                    <div class="price">
                                        ￥
                                        <span class="now">
                                            {{ Money(currentSku.promotionPrice)[0] }}
                                        </span>
                                        .{{ Money(currentSku.promotionPrice)[1] }}
                                    </div>
                                </div>
                                <div class="pro-com">
                                    <span class="com-item">单买价</span>
                                    <span class="old-price">￥{{ Money(currentSku.price)[0] }}.{{ Money(currentSku.price)[1] }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 开团或者参团 -->
                <div class="fight-suc" v-if="fightDetail.groupStatus == 1 || fightDetail.groupStatus == 5">
                    <div class="suc-tit">
                        <div class="fight-state">
                            {{ fightDetail.isSelf == true && fightDetail.peopleNumber > fightDetail.addUserList.length ? '等待成团中' : '' }}
                        </div>
                        <div class="f-num">
                            还差
                            <span class="num">{{ fightDetail.peopleNumber - fightDetail.participantNumber }}人</span>
                            拼购成功，快去邀请{{ fightDetail.groupModel == 'RECRUITMENT_GROUP' ? '未在商城下过单的' : '' }}小伙伴一起拼团
                        </div>
                    </div>
                    <div class="suc-time">
                        <count-down :time="fightDetail.groupEndTime" :custom="true" style="display: inline" @finish="endcallback">
                            <template v-slot="times">
                                剩
                                <div class="time-box" :style="{ color: themes.color }">
                                    <span class="time-item" :style="{ color: themes.color }" v-if="times.times.days > 0">
                                        {{ times.times.days }}
                                    </span>
                                    <template v-if="times.times.days > 0">:</template>
                                    <span class="time-item" :style="{ color: themes.color }">
                                        {{ times.times.hours }}
                                    </span>
                                    :
                                    <span class="time-item" :style="{ color: themes.color }">
                                        {{ times.times.minutes }}
                                    </span>
                                    :
                                    <span class="time-item" :style="{ color: themes.color }">
                                        {{ times.times.seconds }}
                                    </span>
                                </div>
                            </template>
                        </count-down>
                    </div>
                    <div class="suc-partner">
                        <div class="par-item" v-for="(item, index) in fightDetail.addUserList" :key="index">
                            <div class="item-box">
                                <img
                                    :src="
                                        item.isHead == 'true'
                                            ? require('../../assets/images/head-default.png')
                                            : item.portraitPic
                                            ? $imgUrlHead + item.portraitPic
                                            : require('../../assets/images/head-default.png')
                                    "
                                    alt
                                />
                                <span class="par-head" v-if="item.isHead == true">团长</span>
                            </div>
                        </div>
                        <div
                            class="par-item"
                            v-for="(item1, index1) in fightDetail.peopleNumber - fightDetail.addUserList.length"
                            :key="'info2-' + index1"
                        >
                            <div class="item-box">
                                <div class="add-par">？</div>
                            </div>
                        </div>
                    </div>
                    <div class="btn-box" @click="goTuxedo" v-if="fightDetail.isParticipate == false">
                        <div class="btn" style="color: #fff" :class="isfinishEnd ? 'disabled' : 'cur'">立即参团</div>
                    </div>
                    <div class="btn-box" v-if="fightDetail.isParticipate == true">
                        <div class="btn" @click="share" style="color: #fff" :class="isfinishEnd ? 'disabled' : 'cur'">邀请好友</div>
                        <div class="btn" @click="ClickOrderDetails(fightDetail.subNumber)">查看订单</div>
                    </div>
                </div>
                <!-- 开团或者参团 -->

                <!-- 开团成功 -->
                <div class="fight-suc" v-if="fightDetail.groupStatus == 2">
                    <div class="fight-suc-icon">
                        <span class="txt">拼团成功</span>
                    </div>
                    <div class="suc-tit" v-if="fightDetail.isParticipate">
                        <span class="fight-state">恭喜你，拼团成功！</span>
                    </div>
                    <div class="suc-tit">
                        <span class="fight-state">该团已拼团成功，请另开新团或参加别的团!</span>
                    </div>
                    <div class="suc-partner">
                        <div class="par-item" v-for="(item, index) in fightDetail.addUserList" :key="index">
                            <div class="item-box">
                                <img
                                    :src="
                                        item.isHead == 'true'
                                            ? require('../../assets/images/head-default.png')
                                            : item.portraitPic
                                            ? $imgUrlHead + item.portraitPic
                                            : require('../../assets/images/head-default.png')
                                    "
                                    alt
                                />
                                <span class="par-head" v-if="index == 0">团长</span>
                            </div>
                        </div>
                    </div>
                    <div class="btn-box">
                        <div class="btn cur" @click="goTuxedo('finish')" v-if="fightDetail.activeStatus == 1" style="color: #fff">再来一团</div>
                        <div class="btn" v-if="fightDetail.isParticipate && fightDetail.subNumber" @click="ClickOrderDetails(fightDetail.subNumber)">订单详情</div>
                    </div>
                </div>

                <!-- 拼团失败 -->
                <div class="fight-suc" v-if="fightDetail.groupStatus == 3">
                    <div class="suc-tit">
                        <div class="fight-state">拼团失败</div>
                        <div class="f-num">
                            还差
                            <span class="num">{{ fightDetail.peopleNumber - fightDetail.participantNumber }}人</span>
                            拼购成功
                        </div>
                    </div>
                    <div class="suc-partner">
                        <div class="par-item" v-for="(item, index) in fightDetail.addUserList" :key="index">
                            <div class="item-box">
                                <img
                                    :src="
                                        item.isHead == 'true'
                                            ? require('../../assets/images/head-default.png')
                                            : item.portraitPic
                                            ? $imgUrlHead + item.portraitPic
                                            : require('../../assets/images/head-default.png')
                                    "
                                    alt
                                />
                                <span class="par-head" v-if="item.isHead == true">团长</span>
                            </div>
                        </div>
                    </div>
                    <div class="btn-box">
                        <div class="btn cur" @click="goTuxedo('finish')" v-if="fightDetail.activeStatus == 1" style="color: #fff">重新开团</div>
                        <div class="btn" @click="ClickOrderDetails(fightDetail.subNumber)">查看订单</div>
                    </div>
                </div>
            </div>

            <div class="popup-hide" :class="{ show: showSku }">
                <div class="popup-box">
                    <div class="spec-menu">
                        <div class="spec-menu-up">
                            <div class="spec-img" @click="imageSkuPreview()">
                                <legend-image :pic="currentSku.pic" :isJD="fightDetail.prodSource == 'JD'" />
                            </div>
                            <i class="close close-pop" @click="closeAll"></i>
                            <div class="spec-name">{{ currentSku.name }}</div>
                            <span class="spec-price">
                                ￥
                                <em class="price">
                                    {{ Money(currentSku.promotionPrice)[0] }}
                                </em>
                                .{{ Money(currentSku.promotionPrice)[1] }}
                            </span>
                        </div>
                        <div class="spec-menu-middle">
                            <template v-if="skuList">
                                <div class="pro-att clearfix" v-for="(prodProp, prodPropIndex) in skuList" :key="prodPropIndex">
                                    <span class="spec-tit">{{ prodProp.propName }}</span>

                                    <div class="spec-con clearfix">
                                        <div
                                            tag="a"
                                            v-for="(prodPropVal, prodPropValIndex) in prodProp.propValues"
                                            :key="prodPropValIndex"
                                            class="item"
                                            :class="{
                                                on: prodPropVal.isSelect,
                                                itemNot: !prodPropVal.isEnable
                                            }"
                                            @click="currentFilter(prodProp.id, prodPropVal.id, prodPropVal.key)"
                                        >
                                            {{ prodPropVal.propValue }}
                                        </div>
                                    </div>
                                </div>
                            </template>

                            <div class="pro-num clearfix">
                                <span class="spec-tit">
                                    数量
                                    <em style="color: #e2393b; margin-left: 5px" v-if="currentSku.stocks == 0">(库存不足)</em>
                                    （库存：{{ currentSku.stocks }}）
                                </span>
                                <div
                                    v-if="fightDetail.purchaseLimitMode && fightDetail.purchaseLimitMode != 'NOT_LIMIT'"
                                    class="text-danger font-12 d-flex a-center"
                                    style="margin: 12px 5px 0 0"
                                >
                                    <div>
                                        <span>限购：</span>
                                        <span>{{ fightDetail.purchaseLimitAmount }}</span>
                                    </div>
                                </div>
                                <div v-if="fightDetail.startSale" class="text-danger font-12 d-flex a-center" style="margin: 12px 5px 0 5px">
                                    <div>
                                        <span>起售：</span>
                                        <span>{{ fightDetail.startSaleAmount }}</span>
                                    </div>
                                </div>
                                <div class="add-sub">
                                    <a href="javascript:;" class="sub-a" :class="goodsNum == 1 ? 'sub-limit' : ''" @click="reduce">-</a>
                                    <input
                                        type="text"
                                        value="1"
                                        :disabled="currentSku.stocks == 0 || currentSku.status == 0"
                                        class="sub-input"
                                        @keyup="changeGoodsNum"
                                        @blur="checkGoodsNum"
                                        v-model.number="goodsNum"
                                    />
                                    <a
                                        href="javascript:;"
                                        class="sub-a"
                                        :class="goodsNum == currentSku.stocks || currentSku.stocks == 0 ? 'sub-limit' : ''"
                                        @click="add"
                                    >
                                        +
                                    </a>
                                </div>
                            </div>
                        </div>
                        <button
                            v-if="fightDetail.groupStatus == 2 || fightDetail.groupStatus == 3"
                            class="popup-btn"
                            :class="{
                                itemNot: currentSku.stocks == 0 || currentSku.status == 0
                            }"
                            @click="colseSku"
                        >
                            去开团
                        </button>
                        <button
                            v-else
                            class="popup-btn"
                            :class="{
                                itemNot: currentSku.stocks == 0 || currentSku.status == 0
                            }"
                            @click="colseSku"
                        >
                            去参团
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <share-sheet ref="shareSheet" :prames="shareConfig"></share-sheet>

        <div class="popup-haibao" v-if="posterShow">
            <div class="content">
                <img
                    v-if="posterDataUrl"
                    :src="posterDataUrl"
                    class="poster-bg"
                    alt="邀请海报"
                    style="width: 235px; height: 440px; pointer-events: inherit"
                />
                <div class="content-bg" v-else id="poster" ref="poster">
                    <div class="bg-toux">
                        <div class="content-toux">
                            <img
                                :src="posterAttr.pic ? $imgUrlHead + posterAttr.pic : require(`@/assets/images/default-goods-img.jpg`)"
                                class="img"
                                alt
                            />
                        </div>
                        <div class="name">
                            <P class="name-txet">{{ posterAttr.name }}</P>
                            <P class="title">为你推荐好物</P>
                        </div>
                    </div>
                    <div class="proder">
                        <p class="proder-text">{{ fightDetail.name }}</p>
                        <img
                            crossorigin="anonymous"
                            :src="fightDetail.prodPic ? $imgUrlHead + fightDetail.prodPic : require(`@/assets/images/default-goods-img.jpg`)"
                            class="img"
                            alt
                        />
                    </div>
                    <div class="p-price">
                        <p class="Assemble">拼团价：￥{{ fightDetail.minPrice }}</p>
                        <p class="price">原价：￥{{ fightDetail.minProdPrice }}</p>
                    </div>
                    <div class="qrcode" ref="qrcode"></div>
                </div>

                <div class="close" @click="closeCode">
                    <img class="closeImg" src="@/assets/images/close1.png" alt />
                </div>
            </div>
        </div>

        <bind-phone :bindPhone="bindPhone" ref="bindPhone" :bind-scene="'MERGE_GROUP'" />
    </div>
</template>

<script>
import cash from 'utils/tool'
import { mapState } from 'vuex'
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
import countDown from 'components/countdown/count-down'
import shareSheet from 'components/share/shareSheet'
import legendImage from 'components/legendImage/legendImage'
import { groupDetail } from 'api/fight'
import { checkOrderParams } from 'api/goodsDetail'
import { getUserInfo } from 'api/account'
import fightSkuMixin from 'mixin/fightSkuMixin.js'
import { tokenManage } from 'utils/Cache'
import bindPhone from 'components/bindPhone/bindPhone'
import { bindDistri } from 'api/extensionApi'
import { checkPayedSubForUser } from 'api/my'

export default {
    mixins: [fightSkuMixin],
    data() {
        return {
            imgUrl: '',
            showHaibao: false,
            qrcodeFlag: false,
            show: false,
            sn: '',
            source: '',
            fightDetail: '',
            Nomsg: false,
            Money: cash, //价格转换
            showSku: false,
            timer: null,
            posterDataUrl: '',
            fightgroupDetailurl: location.href,
            //头像跟名字
            posterAttr: {
                name: '',
                pic: ''
            },
            isLogin: tokenManage.getToken() ? true : false, //默认没登录

            propObjs: [], // 存改变后的skulist数据
            map: {}, //存cnProperties作为key的数据
            currentSku: {}, //找到isMainSku == true的元素 并且用来渲染页面，数据联动
            cuccentValue: {},
            skuList: [], //用来渲染页面的sku选择
            isfinishEnd: false, //是否已经结束，但后台又没有刷新
            // 绑定手机号相关
            bindPhone: {
                already: false, // 是否已绑定
                showPopup: false
            }
        }
    },
    mounted() {
        this.sn = this.$route.query.sn
        //来源
        this.source = this.$route.query.source == 'SUB' ? 'SUB' : 'GROUP'

        this.loadgroupDetail(this.sn, this.source)

        let that = this
    },
    methods: {
        //获取拼团详情
        loadgroupDetail(sn, source) {
            groupDetail({
                sn,
                source
            }).then((res) => {
                if (res.status == 1) {
                    if (res.result) {
                        // 如果该团已经成团并且用户不是参与者，则提示
                        if (res.result.groupStatus == 2 && !res.result.isParticipate) {
                            this.$toast('该团已完成拼团，您可以重新发团')
                        }

                        this.fightDetail = res.result
                        this.goodsPic = this.fightDetail.prodPic

                        this.checkRelationship(res.result.headInvitationCode)

                        // 商品起售问题
                        if (res.result.startSale) {
                            this.goodsNum = res.result.startSaleAmount
                        }

                        //sku的集合
                        let skuDtoList = this.fightDetail.skuDtoList

                        this.fightDetail.groupStatus == 1 && (this.isfinishEnd = this.fightDetail.groupEndTime - Date.now() > 0 ? false : true)

                        if (skuDtoList[0].cnProperties) {
                            this.propObjs = skuDtoList.map((v) => {
                                return {
                                    ...v,
                                    cnProperties: v.cnProperties.split(';'),
                                    properties: v.properties.split(';'),
                                    key: v.properties,
                                    selectName: v.cnProperties
                                }
                            })

                            this.propObjs.forEach((v) => {
                                this.map[v.key] = v
                            })

                            this.currentSku = this.propObjs.find((v) => v.isMainSku)

                            this.cuccentValue = this.currentSku.properties.reduce((res, cur) => {
                                let arr = cur.split(':')
                                res[arr[0]] = arr[1]
                                return res
                            }, {})

                            this.buildSkuList()
                        } else {
                            //没有sku
                            this.currentSku = skuDtoList[0]
                            this.currentSku.selectName = skuDtoList[0].name
                        }
                    } else {
                        this.Nomsg = true
                    }
                } else {
                    this.$toast(res.msg)
                }
            })
        },

        //去参团
        async goTuxedo(status) {
            // 如果是拉新团，则需要判断用户有没有在商城中消费过
            if (!this.fightDetail.isParticipate && this.fightDetail.groupModel == 'RECRUITMENT_GROUP' && status != 'finish') {
                let result = await checkPayedSubForUser()
                    .then((res) => {
                        if (res.result) {
                            this.$dialog
                                .alert({
                                    title: '提示',
                                    message: '该活动仅限新客户参团，老客户可任意开团'
                                })
                                .then(() => {
                                    this.$router.push({
                                        path: `/fightDetail`,
                                        query: {
                                            id: this.fightDetail.mergeId
                                        }
                                    })
                                })

                            return false
                        }
                        return true
                    })
                    .catch((err) => {
                        return true
                    })

                if (!result) return
            }

            !this.isfinishEnd && (this.showSku = true)

            // 如果是以完成拼团状态，则再来一团
            if (this.fightDetail.groupStatus == 2) {
                this.showSku = true
            }
        },
        colseSku() {
			if (this.currentSku.stocks == 0) {
			    this.$toast('此选择的商品库存为0~~~')
			    return
			}
			
			if (this.goodsNum == 0) {
			    this.$toast('此选择的商品数量不能为0~~~')
			    return
			}
            this.$utils.uDebounce(() => {
				let addNumber = ''
				
				if (this.fightDetail.groupStatus == 1) {
				    addNumber = this.fightDetail.isParticipate ? '' : this.fightDetail.groupNumber
				}
				
				if (this.fightDetail.groupStatus == 3 || this.fightDetail.groupStatus == 2) {
				    addNumber = ''
				}
				
				let query = {
				    type: 'MERGE_GROUP',
				    addNumber: addNumber,
				    activeId: this.fightDetail.mergeId,
				    count: this.goodsNum,
				    prodId: this.fightDetail.prodId,
				    skuId: this.currentSku.skuId,
				    buyNow: true
				}
				checkOrderParams(query).then((res) => {
				    if (res.status === -501) {
				        // this.bindPhone.showPopup = true
						this.$utils.goLoginPage(this)
						// this.$router.replace({ path: '/login', query: { redirect: this.$route.fullPath } })
				        return
				    }
				
				    if (res.status != 1) {
				        this.$toast(res.msg)
				
				        // 起售判断
				        if (this.fightDetail.startSale) {
				            this.goodsNum = this.fightDetail.startSaleAmount
				            return
				        }
				
				        // 限购判断
				        if (this.fightDetail.purchaseLimitMode != 'NOT_LIMIT') {
				            this.goodsNum = this.fightDetail.purchaseLimitAmount
				            return
				        }
				
				        return
				    }
				
				    this.$router.push({
				        path: `/submitOrder`,
				        query
				    })
				})
			})
        },

        closeAll() {
            this.showSku = false
            this.shareConfig.shareText = `还差${
                this.fightDetail.peopleNumber - this.fightDetail.participantNumber
            }拼购成功，快去邀请小伙伴一起拼团！${this.fightgroupDetailurl}`
        },

        //查看订单详情
        ClickOrderDetails(subNumber) {
            if (subNumber) {
                this.$router.push({
                    path: `/orderDetail`,
                    query: {
                        subNumber: subNumber
                    }
                })
            }
        },
        endcallback() {
            this.loadgroupDetail(this.sn, this.source)
        },
        async createQRCode() {
            // 配置项
            const options = {
                width: 80,
                height: 80,
                background: '#ffffff',
                colorDark: '#000000',
                margin: 1
            }
            const result = await QRCode.toDataURL(`${this.fightgroupDetailurl}`, options)
            const images = document.createElement('img')
            images.setAttribute('src', result)
            this.$refs.qrcode.appendChild(images)

            // 手动创建一个 canvas 标签
            let canvas = document.createElement('canvas')
            // // 获取父标签，意思是这个标签内的 DOM 元素生成图片
            let canvasBox = this.$refs.poster

            const options1 = {
                allowTaint: true,
                taintTest: false,
                useCORS: true
            }

            // setTimeout(() =>{
            html2canvas(canvasBox, options1).then((canvas) => {
                // toDataURL 图片格式转成 base64
                let dataURL = canvas.toDataURL('image/jpeg', 1.0)

                this.posterDataUrl = dataURL
            })
            // },300)
        },
        share() {
            if (this.isfinishEnd) {
                return
            }
            this.$refs.shareSheet.sheetShow = true
            this.shareConfig.shareText = `【${this.fightDetail.prodName}】还差${
                this.fightDetail.peopleNumber - this.fightDetail.participantNumber
            }人拼购成功，快去邀请小伙伴一起拼团！${this.fightgroupDetailurl}`
            if (!this.posterDataUrl) {
                if (this.isLogin) {
                    getUserInfo()
                        .then((res) => {
                            if (res.status == 1) {
                                this.posterAttr.name = res.result.nickName
                                this.posterAttr.pic = res.result.headPortrait
                            } else {
                                this.posterAttr.name = '匿名'
                                this.posterAttr.pic = ''
                            }
                        })
                        .catch(() => {
                            this.posterAttr.name = '匿名'
                            this.posterAttr.pic = ''
                        })
                } else {
                    this.posterAttr.name = '匿名'
                    this.posterAttr.pic = ''
                }
            }
        },

        // 查看订单是否有邀请码
        checkRelationship(invitCode) {
            bindDistri({ invitationCode: invitCode, bindScene: 'MERGE_GROUP' }).then((res) => {})
        }
    },
    components: {
        QRCode,
        countDown,
        shareSheet,
        legendImage,
        bindPhone
    },
    computed: {
        ...mapState(['themes'])
    }
}
</script>

<style src="../../assets/css/style/fight-style.css" scoped></style>
<style src="../../assets/css/style/list-style.css" scoped></style>
<style src="../../assets/css/style/detail-style.css" scoped></style>
<style src="../../assets/css/style/popup-style.css" scoped></style>
<style src="../../assets/css/detail.css" scoped></style>
<style src="../../assets/css/fight.css" scoped></style>
<style src="../../assets/css/popup.css" scoped></style>
<style src="../../assets/css/search.css" scoped></style>

<style lang="stylus" scoped>
.share-goods {
  min-height: 140px;

  .share-des {
    padding: 0 15px;
    color: #999;
    line-height: 20px;
    font-size: 12px;
    margin-top: 15px;
  }

  .share-way {
    display: flex;

    .item {
      flex: 1;
      text-align: center;
      padding: 15px 0 15px;

      .img {
        border-radius: 50%;
        width: 50px;
        height: 50px;
        line-height: 50px;
        margin: auto;
        font-size: 0;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .txt {
        margin-top: 10px;
        font-size: 14px;
      }
    }
  }
}

.pro-img .haitao {
  position: absolute;
  top: 0;
  left: 0px;
  width: 30px !important;
  height: 30px !important;
}
</style>
